/**
 * 字典 util
 * author: scott
 * date: 20190109
 */

import { ajaxGetDictItems, getDictItemsFromCache } from '@/api/api'
import Vue from 'vue'
import { UI_CACHE_DB_DICT_DATA } from '@/store/mutation-types'
import message from 'ant-design-vue/es/message'

/**
 * 根据字典code数组，来获取对应字典数组
 * @param dictCodeList 字典Code数组
 * @return List<Map> 二维数组，包括每个字典值数组的数组
 * @author kai
 */
export const initDictOptionsByDictCodeList = (dictCodeList) => {
  return new Promise((resolve, reject) => {
    if (!(dictCodeList instanceof Array)) {
      return reject({ success: false, message: '参数dictCodeList必须为数组！' })
    }
    if (dictCodeList.length === 0) {
      return reject({ success: false, message: '字典数组不能为空！' })
    }
    let promiseList = []
    // 注册Promise对象数组
    for (const dictCode of dictCodeList) {
      let promiseItem = new Promise((resolve, reject) => {
        initDictOptions(dictCode).then((res) => {
          if (!res.success) {
            message.warning(`请求字典值【${dictCode}】失败！`)
            reject(res)
          }
          resolve(res)
        })
      })
      promiseList.push(promiseItem)
    }
    Promise.all(promiseList).then(resultList => {
      resolve(resultList)
    }).catch(res => {
      reject(res)
    })
  })
}

/**
 * 获取字典数组，优先从缓存中读取字典配置，没有就请求后台，并把结果存储到缓存。
 * @param dictCode 字典Code
 * @return List<Map>
 * @author kai
 */
export async function initDictOptions(dictCode) {
  if (!dictCode) {
    return '字典Code不能为空!'
  }
  // 优先从缓存中读取字典配置
  if (getDictItemsFromCache(dictCode)) {
    let res = {}
    res.result = getDictItemsFromCache(dictCode)
    res.success = true
    return res
  }
  // 获取字典数组
  let res = await ajaxGetDictItems(dictCode)
  // 存到缓存里
  let codeData = Vue.ls.get(UI_CACHE_DB_DICT_DATA)
  codeData[dictCode] = res.result
  Vue.ls.set(UI_CACHE_DB_DICT_DATA, codeData, 7 * 24 * 60 * 60 * 1000)
  return res
}

/**
 * 字典值替换文本通用方法
 * @param dictOptions  字典数组
 * @param text  字典值
 * @return String
 */
export function filterDictText(dictOptions, text) {
  if (text != null && Array.isArray(dictOptions)) {
    let result = []
    // 允许多个逗号分隔，允许传数组对象
    let splitText
    if (Array.isArray(text)) {
      splitText = text
    } else {
      splitText = text.toString().trim().split(',')
    }
    for (let txt of splitText) {
      let dictText = txt
      for (let dictItem of dictOptions) {
        if (txt.toString() === dictItem.value.toString()) {
          dictText = (dictItem.text || dictItem.title || dictItem.label)
          break
        }
      }
      result.push(dictText)
    }
    return result.join(',')
  }
  return text
}

/**
 * 字典值替换文本通用方法(多选)
 * @param dictOptions  字典数组
 * @param text  字典值
 * @return String
 * @author kai
 */
export function filterMultiDictText(dictOptions, text) {
  // js “!text” 认为0为空，所以做提前处理
  if (text === 0 || text === '0') {
    if (dictOptions) {
      for (let dictItem of dictOptions) {
        if (text == dictItem.value) {
          return dictItem.text
        }
      }
    }
  }

  if (!text || text == 'null' || !dictOptions || dictOptions.length == 0) {
    return ''
  }
  let re = ''
  text = text.toString()
  let arr = text.split(',')
  dictOptions.forEach(function(option) {
    if (option) {
      for (let i = 0; i < arr.length; i++) {
        if (arr[i] === option.value) {
          re += option.text + ','
          break
        }
      }
    }
  })
  if (re == '') {
    return text
  }
  return re.substring(0, re.length - 1)
}

/**
 * 翻译ids类型对应的文本，结果以','分割
 * @param dictCode 字典code
 * @param keys ids的值，如"1587689746070056961,1586951030911033345"
 * @returns {string|*} 如"美术与设计学院,文学与新闻传播学院"
 */
export function filterIdsDictTextByCache(dictCode, keys) {
  if (keys == null || keys.length == 0) {
    return
  }
  if (!dictCode) {
    return '字典Code不能为空!'
  }
  let keyList = keys.split(',')
  return keyList.map((key) => {
    // 优先从缓存中读取字典配置
    if (getDictItemsFromCache(dictCode)) {
      let item = getDictItemsFromCache(dictCode).filter(t => t['value'] == key)
      if (item && item.length > 0) {
        return item[0]['text']
      }
    } else {
      return ''
    }
  }).join(',')
}

/**
 * 翻译字段值对应的文本
 * @param children
 * @returns string
 */
export function filterDictTextByCache(dictCode, key) {
  if (key == null || key.length == 0) {
    return
  }
  if (!dictCode) {
    return '字典Code不能为空!'
  }
  // 优先从缓存中读取字典配置
  if (getDictItemsFromCache(dictCode)) {
    let item = getDictItemsFromCache(dictCode).filter(t => t['value'] == key)
    if (item && item.length > 0) {
      return item[0]['text']
    }
  }
}
